package com.sc.generatorcode.task;

import com.sc.generatorcode.entity.ColumnInfo;
import com.sc.generatorcode.task.base.AbstractTask;
import com.sc.generatorcode.utils.ConfigUtil;
import com.sc.generatorcode.utils.FileUtil;
import freemarker.template.TemplateException;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

public class VueRouteTask extends AbstractTask {

    public VueRouteTask(String className, List<ColumnInfo> infos) {
        super(className,infos);
    }

    @Override
    public void run() throws IOException, TemplateException {
        String name = super.getName()[1];

        String rootDir = System.getProperty("user.dir");
        String vueRouteDir = rootDir + "\\gen";
        FileUtil.mkdirs(vueRouteDir);
        String fileName = "VueRoute.txt";

        String vuePath = ConfigUtil.getConfiguration().getPath().getVueDir();

        String pageName = name.substring(0,1).toUpperCase().concat(name.substring(1).toLowerCase()).concat("List");
        String pageFileName = name.concat("-list.vue");
        String pagePackage = "import ".concat(pageName).concat(" from").concat("'@/").concat((vuePath.substring(vuePath.indexOf("src") + 4).replaceAll("\\\\","/"))).concat("/").concat(name).concat("/").concat(pageFileName).concat("'");
        try {
            StringBuffer content = new StringBuffer(pagePackage);
            content.append("\n");
            content.append("export default [");
            content.append("\n");
            content.append("\t{");
            content.append("\n");
            content.append("\t\tpath: '/").append(pageName).append("',");
            content.append("\n");
            content.append("\t\tcomponent: ").append(pageName);
            content.append("\n");
            content.append("\t}");
            content.append("\n");
            content.append("]");

            File file = new File(vueRouteDir);
            if(!file.exists()){
                file.mkdirs();
            }

            file = new File(vueRouteDir + File.separator + fileName);
            file.createNewFile();
            BufferedWriter out = new BufferedWriter(new FileWriter(file));
            out.write(content.toString());
            out.flush();
            out.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
